<!DOCTYPE html>
<html>
  <head>
    <title>JSON_SCADA Login Form</title>
    <link rel="stylesheet" type="text/css" href="login.css" />
    <style>
      .blocks {
        display: flex;
        flex: 0 1 min-content;
        position: relative;
        float: left;
        flex-wrap: wrap;
        background-color: rgb(141, 160, 182);
        color: white;
        vertical-align: middle;
        margin: 5px;
        padding: 5px;
        box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
        border-radius: 3px;
        transition: 1s;
      }
      h1 {
        text-align: center;
      }
      a {
        text-align: center;
      }
      a:link {
        text-decoration: none;
        color: inherit;
      }

      a:visited {
        text-decoration: none;
        color: inherit;
      }

      a:hover {
        text-decoration: underline;
        color: inherit;
      }

      a:active {
        text-decoration: underline;
        color: inherit;
      }
      body {
        font-family: calibri, helvetica, arial;
        font-size: 20px;
        background: linear-gradient(to bottom, #deefff 0%, #98bede 100%);
        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;
      }
      html {
        height: 100%;
      }
    </style>
    <script>
      String.prototype.trim = function () {
        return this.replace(/^\s+|\s+$/g, '')
      }

      const parseCookie = str => {
        if (str === '') return {}
        return str
          .split(';')
          .map(v => v.split('='))
          .reduce((acc, v) => {
            acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(
              v[1].trim()
            )
            return acc
          }, {})
      }

      function LoadFavicon (href) {
        var link = document.createElement('link')
        link.type = 'image/x-icon'
        link.rel = 'shortcut icon'
        link.href = href
        document.getElementsByTagName('head')[0].appendChild(link)
      }

      function testLogin () {
        var ck = parseCookie(document.cookie)
        if ('json-scada-user' in ck) {
          ck = JSON.parse(ck['json-scada-user'])
          var logoutButton = document.getElementById('logout')
          var buttonMessage = 'Logout [' + ck.username + ']'
          if (logoutButton.textContent !== buttonMessage)
            logoutButton.textContent = buttonMessage

          if (ck.rights.isAdmin)
            document.getElementById('divAdmin').style.display = ''
          else document.getElementById('divAdmin').style.display = 'none'
        }

        fetch('/Invoke/test/user', {
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
          },
          method: 'GET'
        })
          .then(resp => resp.json())
          .then(data => {
            // console.log(data)
            if ('ok' in data && data.ok) {
              document.getElementById('divlogout').style.display = ''
              document.getElementById('divlogin').style.display = 'none'
              document.getElementById('divloginerror').style.display = 'none'
            } else {
              document.getElementById('divlogout').style.display = 'none'
              document.getElementById('divlogin').style.display = ''
            }
          })
          .catch(error => {
            document.getElementById('divlogout').style.display = 'none'
            document.getElementById('divlogin').style.display = ''
            console.log(
              'There has been a problem with your fetch operation: ' +
                error.message
            )
          })
      }

      function tryLogin (e) {
        fetch('/Invoke/auth/signin', {
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
          },
          method: 'POST',
          body: JSON.stringify({
            username: document.getElementById('username').value,
            password: document.getElementById('password').value
          })
        })
          .then(resp => resp.json())
          .then(data => {
            if ('ok' in data && data.ok == false) {
              document.getElementById('divloginerror').style.display = ''
              setTimeout(function () {
                document.getElementById('divloginerror').style.display = 'none'
              }, 3000)
            }
          })
          .catch(error => {
            console.log('Error on a fetch operation: ' + error.message)
          })
          .finally(() => {
            testLogin()
          })
      }

      function tryLogout (e) {
        fetch('/Invoke/auth/signout', {
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
          },
          method: 'POST',
          body: JSON.stringify({
            username: document.getElementById('username').value
          })
        })
          .then(response => {
            // console.log(response)
          })
          .catch(error => {
            console.log('Error on a fetch operation: ' + error.message)
          })
          .finally(() => {
            testLogin()
          })
      }
    </script>
  </head>
  <body>
    <div id="divlogin" class="login" style="display:none">
      <h1>
        <img height="90" src="images/json-scada.svg" alt="{json:scada}" />
        <br />Login
      </h1>

      <input
        type="text"
        name="username"
        id="username"
        placeholder="Username"
        required="required"
      />
      <input
        type="password"
        name="password"
        id="password"
        placeholder="Password"
        required="required"
      />
      <button
        type="button"
        id="login"
        onclick="tryLogin()"
        class="btn btn-primary btn-block btn-large"
      >
        LOGIN
      </button>

      <div id="divloginerror" style="display:none">
        Login error, invalid credentials!
      </div>
    </div>

    <div id="divlogout" style="display:none">
      <h1>
        <img height="90" src="images/json-scada.svg" alt="{json:scada}" />
      </h1>

      <button
        id="logout"
        type="button"
        onclick="tryLogout()"
        class="blocks btn btn-primary"
      >
        LOGOUT
      </button>

      <div class="blocks">
        <a target="_blank" href="../display.html?SVGFILE=../svg/kaw2.svg">
          <img height="40" src="images/tela.png" /><br />Display Viewer
        </a>
      </div>
      <div class="blocks">
        <a target="_blank" href="../tabular.html?MODE=ALARMS_VIEWER">
          <img height="40" src="images/firstaid.svg" /><br />Alarms Viewer
        </a>
      </div>
      <div class="blocks">
        <a target="_blank" href="../events.html">
          <img height="40" src="images/chrono.svg" /><br />Events Viewer
        </a>
      </div>
      <div class="blocks">
        <a target="_blank" href="../tabular.html">
          <img height="40" src="images/tabular.svg" /><br />Tabular Viewer
        </a>
      </div>
      <div class="blocks" title="Grafana">
        <a id="grafana" target="_blank" href="/grafana">
          <img height="40" src="images/grafana.ico" /><br />Grafana Dashboards
        </a>
        <script>
          // use this to access Grafana on a distinct port or use some reverse proxy and remove this code
          //(function () {
          // document.getElementById('grafana').href = window.location.protocol + "//" + window.location.hostname + ":3000";
          // })();
        </script>
      </div>

      <div class="blocks">
        <a target="_blank" href="../about.html">
          <img height="40" src="images/json-scada.svg" /><br />About JSON SCADA
        </a>
      </div>

      <div
        class="blocks"
        id="divAdmin"
        title="Administrative Panel"
        style="display:none"
      >
        <a target="_blank" href="../admin/">
          <img height="40" src="images/admin.png" /><br />Admin
        </a>
      </div>
    </div>

    <script>
      ;(function () {
        LoadFavicon('images/favicon.ico')
        testLogin()
        setInterval(testLogin, 5000)

        document
          .getElementById('password')
          .addEventListener('keyup', function (event) {
            if (event.keyCode === 13) {
              event.preventDefault()
              document.getElementById('login').click()
            }
          })
      })()
    </script>
  </body>
</html>
